import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/common_title_edit_with_underline_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/camera/front_camera_head/front_camera_head_page.dart';
import 'package:e_reception_flutter/ui/company/company_add_user_edit_info/bean/company_add_user_edit_info_type.dart';
import 'package:e_reception_flutter/ui/company/company_add_user_edit_info/bean/company_add_user_edit_info_upload_bean.dart';
import 'package:e_reception_flutter/ui/company/company_choose_terminal_list/bean/company_choose_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_choose_terminal_list/company_choose_terminal_list_page.dart';
import 'package:e_reception_flutter/ui/mark/choose_group/choose_group_page.dart';
import 'package:e_reception_flutter/ui/mark/matching_or_mark/bean/matching_info_bean.dart';
import 'package:e_reception_flutter/ui/mark/matching_or_mark/bean/matching_or_mark_upload_bean.dart';
import 'package:e_reception_flutter/ui/mypage/edit_name_dialog_widget.dart';
import 'package:e_reception_flutter/utils/common_select_util.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/clip_image_head_border/clip_image_head_border_utils.dart';
import 'package:e_reception_flutter/vg_widgets/clip_image_head_border/logo_detail_page.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:vg_base/vg_string_util_lib.dart';

/// 匹配/标记用户-编辑框
///
/// @author: zengxiangxi
/// @createTime: 1/27/21 5:39 PM
/// @specialDemand:
class MatchingOrMarkEditInfoWidget extends StatefulWidget {
  final ValueNotifier<MatchingOrMarkUploadBean> onChanged;
  final MatchingInfoBean matchingInfoBean;

  const MatchingOrMarkEditInfoWidget(
      {Key key, this.onChanged, this.matchingInfoBean})
      : super(key: key);

  @override
  _MatchingOrMarkEditInfoWidgetState createState() =>
      _MatchingOrMarkEditInfoWidgetState();
}

class _MatchingOrMarkEditInfoWidgetState
    extends State<MatchingOrMarkEditInfoWidget> {
  MatchingOrMarkUploadBean _uploadBean;

  TextEditingController _nameController;

  @override
  void initState() {
    super.initState();
    _uploadBean = MatchingOrMarkUploadBean()
      ..identityType = CompanyAddUserEditInfoIdentityExtension.getIdToTypeStr(
          widget?.matchingInfoBean?.roleid)
      ..name = widget?.matchingInfoBean?.name
      ..nick = widget?.matchingInfoBean?.nick
      ..phone = widget?.matchingInfoBean?.phone
      ..id = widget?.matchingInfoBean?.number
      ..groupName = widget?.matchingInfoBean?.groupName
      ..groupId = widget?.matchingInfoBean?.groupId;
    _notifyChange();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: _toMainColumnWidget(),
    );
  }

  ///通知更新
  _notifyChange() {
    print(_uploadBean?.toString());

    if (widget?.onChanged == null) {
      return;
    }
    if (_uploadBean == null) {
      return;
    }
    Future(() {
      widget.onChanged.value = _uploadBean;
      print("change: ${_uploadBean?.toString()}");
    });
  }

  Widget _toMainColumnWidget() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        _toNameAndNickWidget(),
        _toSplitLineWidget(),
        _toPhoneWidget(),
        _toSplitLineWidget(),
        _toIdWidget(),
        _toSplitLineWidget(),
        _toGroupWidget(),
        _toSplitLineWidget(),
        _toIdentityWidget(),
        // Offstage(
        //     offstage: !_uploadBean.isCommonAdminRole(),
        //     child: _toSplitLineWidget()),
        // Offstage(
        //     offstage: !_uploadBean.isCommonAdminRole(),
        //     child: _toTerminalWidget()),
        // Offstage(
        //     offstage: !_uploadBean.isSuperAdminRole(),
        //     child: _toSplitLineWidget()),
        // Offstage(
        //   offstage: !_uploadBean.isSuperAdminRole(),
        //   child: _toSuperAdminTerminalWidget(),
        // ),
      ],
    );
  }

  Widget _toSplitLineWidget() {
    return Container(
      height: 0.5,
      margin: const EdgeInsets.only(left: 15, right: 1),
      color: ThemeRepository.getInstance().getLineColor_3A3F50(),
    );
  }

  Widget _toPicWidget() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
      child: Row(
        children: <Widget>[
          Container(
            width: 45,
            alignment: Alignment.centerLeft,
            child: Text(
              "照片",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: ThemeRepository.getInstance()
                    .getTextMinorGreyColor_808388(),
                fontSize: 14,
              ),
            ),
          ),
          Expanded(
            child: Container(
              alignment: Alignment.centerLeft,
              child: Text(
                "请务必上传正面清晰人脸照片",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: VgColors.INPUT_BG_COLOR,
                  fontSize: 12,
                ),
              ),
            ),
          ),
          SizedBox(
            width: 5,
          ),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              onClickUserLogo();
            },
            child: ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: Container(
                width: 80,
                height: 80,
                child: VgCacheNetWorkImage(
                  _uploadBean?.picUrl ?? "",
                  emptyWidget:
                      Image.asset("images/binding_terminal_add_pic_ico.png"),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void onClickUserLogo() {
    FocusScope.of(context).requestFocus(FocusNode());
    if (StringUtils.isNotEmpty(_uploadBean.picUrl)) {
      LogoDetailPage.navigatorPush(context,
          url: _uploadBean.picUrl,
          selectMode: SelectMode.HeadBorder,
          clipCompleteCallback: (path, cancelLoadingCallback) {
            _uploadBean.picUrl = path;
            _notifyChange();
            setState(() {});
          }
      );
      return;
    }
    addUserLogo();
  }

  void addUserLogo() {
    CommonMoreMenuDialog.navigatorPushDialog(context, {
      "上传图片": () async {
        String path = await ClipImageHeadBorderUtil.clipOneImage(context,
            scaleY: 1, scaleX: 1, maxAutoFinish: true,
            isShowHeadBorderWidget: true);
        if (path == null || path == "") {
          return;
        }
        _uploadBean.picUrl = path;
        _notifyChange();
        setState(() {});
      },
      "拍照": () async {
        String path = await FrontCameraHeadPage.navigatorPush(context);
        if (path == null || path.isEmpty) {
          return;
        }
        _uploadBean.picUrl = path;
        _notifyChange();
        setState(() {});
      }
    });
  }

  Widget _toNameAndNickWidget() {
    return Row(
      children: <Widget>[
        Expanded(
          child: _EditTextWidget(
            isShowRedStar: true,
            title: "姓名",
            hintText: "请输入",
            maxZHCharLimit: 20,
            controller: _nameController,
            initContent: _getNameAndNickSplitStr(),
            limitCharFunc: (int limit) {
              VgToastUtils.toast(context, "姓名最多${limit ?? 0}个字");
            },
            onDecodeResult: (dynamic result){
              if(result == null || result is! Map){
                return null;
              }
              _uploadBean?.name = result[EDIT_NAME_AND_NICK_BY_NAME_KEY];
              _uploadBean?.nick = result[EDIT_NAME_AND_NICK_BY_NICK_KEY];
              _nameController.text = _getNameAndNickSplitStr();
              return null;

            },
            onChanged: (String editText, dynamic value) {
              _uploadBean?.name = editText;
              _uploadBean?.nick = value;
              _notifyChange();
            },
            readOnly: true,
          ),
        ),
        Container(
          width: 0.5,
          height: 18,
          color: ThemeRepository.getInstance().getLineColor_3A3F50(),
        ),
        // Expanded(
        //   child: _EditTextWidget(
        //     isShowRedStar: false,
        //     title: "昵称",
        //     hintText: "英文名/备注名",
        //     maxZHCharLimit: 20,
        //     initContent: _uploadBean?.nick,
        //     limitCharFunc: (int limit) {
        //       VgToastUtils.toast(context, "姓名最多${limit ?? 0}个字");
        //     },
        //     onChanged: (String editText, dynamic value) {
        //       _uploadBean?.nick = editText;
        //       _notifyChange();
        //     },
        //   ),
        // ),
      ],
    );
  }

  String _getNameAndNickSplitStr(){
    StringBuffer stringBuffer = StringBuffer();
    if(StringUtils.isNotEmpty(_uploadBean?.nick)) {
      stringBuffer.write(VgStringUtils.subStringAndAppendSymbol(
          _uploadBean?.name, 7, symbol: "..."));
    }else{
      stringBuffer.write(_uploadBean?.name);
    }
    if(StringUtils.isNotEmpty(_uploadBean?.nick)){
      stringBuffer.write(" / ");
      stringBuffer.write(VgStringUtils.subStringAndAppendSymbol(_uploadBean?.nick, 7,symbol: "..."));
    }
    return stringBuffer.toString();
  }

  Widget _toPhoneWidget() {
    return _EditTextWidget(
      isShowRedStar: false,
      title: "手机",
      hintText: "请输入",
      initContent: _uploadBean?.phone,
      inputFormatters: [
        WhitelistingTextInputFormatter(RegExp("[0-9+]")),
        LengthLimitingTextInputFormatter(DEFAULT_PHONE_LENGTH_LIMIT),
      ],
      onChanged: (String editText, dynamic value) {
        _uploadBean?.phone = editText;
        _notifyChange();
      },
      readOnly: StringUtils.isEmpty(_uploadBean?.phone) ? false : true,
    );
  }

  Widget _toIdWidget() {
    return _EditTextWidget(
      isShowRedStar: false,
      title: "编号",
      hintText: "员工号/学号等",
      initContent: _uploadBean?.id,
      inputFormatters: [
        WhitelistingTextInputFormatter(RegExp("[A-Za-z0-9+]")),
      ],
      maxZHCharLimit: 15,
      limitCharFunc: (int limit) {
        VgToastUtils.toast(context, "编号最多${limit ?? 0}个字");
      },
      onChanged: (String editText, dynamic value) {
        _uploadBean?.id = editText;
        _notifyChange();
      },
    );
  }

  Widget _toGroupWidget() {
    return _EditTextWidget(
      title: "分组",
      hintText: "请选择",
      isShowRedStar: true,
      isShowGoIcon: true,
      initContent: _uploadBean?.groupName,
      onTap: (String editText, dynamic value) {
        return ChooseGroupPage.navigatorPush(context, value);
      },
      onDecodeResult: (dynamic result) {
        if (result is EditTextAndValue) {
          return result;
        }
        return null;
      },
      onChanged: (String editText, dynamic value) {
        _uploadBean.groupName = editText;
        _uploadBean.groupId = value;
        _notifyChange();
      },
    );
  }

  Widget _toIdentityWidget() {
    return _EditTextWidget(
      title: "身份",
      hintText: "请选择",
      isShowRedStar: true,
      isShowGoIcon: true,
      initContent: _uploadBean?.identityType?.getTypeToStr(),
      onTap: (String editText, dynamic value) {
        return null;
        // return SelectUtil.showListSelectDialog(
        //   context: context,
        //   title: "身份",
        //   positionStr: _uploadBean?.identityType?.getTypeToStr(),
        //   textList: CompanyAddUserEditInfoIdentityExtension.getListStr(),
        // );
      },
      onDecodeResult: (dynamic result) {
        if (result is String && StringUtils.isNotEmpty(result)) {
          return EditTextAndValue(
              editText: result,
              value:
                  CompanyAddUserEditInfoIdentityExtension.getStrToType(result));
        }
        return null;
      },
      onChanged: (String editText, dynamic value) {
        // _uploadBean.identityName = editText;
        _uploadBean.identityType = value;
        _notifyChange();
        setState(() {});
      },
    );
  }

  Widget _toTerminalWidget() {
    return _EditTextWidget(
      title: "终端",
      hintText: _uploadBean.isSuperAdminRole() ? "全部终端" : "请选择",
      isShowRedStar: false,
      isShowGoIcon: true,
      onTap: (String editText, dynamic value) {
        if (_uploadBean.isSuperAdminRole()) {
          return null;
        }
        return CompanyChooseTerminalListPage.navigatorPush(
            context, _uploadBean?.terminalList);
      },
      onDecodeResult: (dynamic result) {
        if (result is! List<CompanyChooseTerminalListItemBean>) {
          return null;
        }
        List<CompanyChooseTerminalListItemBean> resultList = result;
        String editTextStr;
        if (resultList == null || resultList.isEmpty) {
          editTextStr = "";
        } else if (resultList.length == 1) {
          editTextStr = resultList?.elementAt(0)?.terminalName;
          //处理空名字
          if (StringUtils.isEmpty(editTextStr)) {
            editTextStr = "1个终端";
          }
        } else {
          editTextStr = "${resultList?.length ?? 0}个终端";
        }
        EditTextAndValue editTextAndValue = EditTextAndValue(
          editText: editTextStr,
          value: result,
        );
        return editTextAndValue;
      },
      onChanged: (String editText, dynamic value) {
        _uploadBean.terminalList = value;
        _notifyChange();
      },
    );
  }

  Widget _toSuperAdminTerminalWidget() {
    return _EditTextWidget(
      title: "终端",
      hintText: "全部终端",
      isShowRedStar: false,
      isShowGoIcon: true,
      onTap: (String editText, dynamic value) {
        return null;
      },
      onDecodeResult: (dynamic result) {
        return null;
      },
      onChanged: (String editText, dynamic value) {},
    );
  }
}

/// 编辑框组件
///
/// @author: zengxiangxi
/// @createTime: 1/18/21 10:55 PM
/// @specialDemand:
class _EditTextWidget extends StatelessWidget {
  final String title;

  final String hintText;

  final CommonTitleEditEditAndValueChangedCallback onChanged;

  ///点击
  final CommonTitleNavigatorPushCallback onTap;

  ///解析跳转返回值
  final CommonTitlePopResultDecodeCallback onDecodeResult;

  final bool isShowRedStar;

  ///中字极限
  final int maxZHCharLimit;

  ///极限字数回调
  final ValueChanged<int> limitCharFunc;

  ///限制
  final List<TextInputFormatter> inputFormatters;

  ///是否显示跳转icon
  final bool isShowGoIcon;

  ///初始化数据
  final String initContent;

  final bool readOnly;

  const _EditTextWidget(
      {Key key,
      this.title,
      this.hintText,
      this.onChanged,
      this.isShowRedStar = false,
      this.onTap,
      this.onDecodeResult,
      this.maxZHCharLimit,
      this.limitCharFunc,
      this.inputFormatters,
      this.isShowGoIcon = false,
      this.initContent,
      this.readOnly, controller})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CommonTitleEditWithUnderlineWidget(
      titleTextStyle: TextStyle(
          color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
          fontSize: 14),
      editTextStyle: TextStyle(
          color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
          fontSize: 14),
      titleWidth: 43,
      title: title,
      height: 50,
      onChanged: onChanged,
      onDecodeResult: onDecodeResult,
      onTap: onTap,
      minLines: 1,
      maxLines: 1,
      readOnly: readOnly,
      maxZHCharLimit: maxZHCharLimit,
      limitCharFunc: limitCharFunc,
      inputFormatters: inputFormatters,
      lineMargin: const EdgeInsets.only(left: 15, right: 0),
      lineUnselectColor: Color(0xFF303546),
      lineHeight: 0,
      initContent: initContent,
      lineSelectedColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      hintText: hintText,
      hintTextStyle: TextStyle(
          color: ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
          fontSize: 14),
      rightWidget: Opacity(
        opacity: isShowGoIcon ? 1 : 0,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 15),
          child: Image.asset(
            "images/go_ico.png",
            width: 6,
            color: VgColors.INPUT_BG_COLOR,
          ),
        ),
      ),
      leftWidget: Container(
        width: 15,
        child: Opacity(
          opacity: isShowRedStar ? 1 : 0,
          child: Center(
            child: Padding(
              padding: const EdgeInsets.only(top: 5),
              child: Text(
                "*",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color:
                        ThemeRepository.getInstance().getMinorRedColor_F95355(),
                    fontSize: 14,
                    height: 1.1),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
